package com.sixfoot.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.sixfoot.domain.Resource;
import com.sixfoot.domain.scale.Scale;
import com.sixfoot.foundation.persistence.springdata.PagedList;
import com.sixfoot.foundation.service.dynamic.AbstractSpecificationService;

@Service
@Transactional
public class ScaleService extends AbstractSpecificationService<Scale, String> {
	
	public PagedList<Scale> findByResourceId(String resourceId, int pageNum, int pageSize) {
		Resource resource = new Resource();
		resource.setId(resourceId);
		
		List<Order> orders = new ArrayList<Order>();
		orders.add(new Order(Direction.DESC, "id"));
		Sort sort = new Sort(orders);
	    Pageable pageable = new PageRequest(pageNum, pageSize, sort);
//	    Pageable pageable = SortFilter.toPageable(pageNum, pageSize, orders);
//		List<Scale> scaleList = ((ScaleRepository) this.getRepository()).findAll(pageable).findByResourceId(resourceId, pageable);
	    Specification<Scale> specification = new Specification<Scale>() {  
	    	public Predicate toPredicate(Root<Scale> root,  
	                CriteriaQuery<?> query, CriteriaBuilder cb) { 
	    		query.where(cb.equal(root.get("resource").as(Resource.class), resource));
	    		return query.getRestriction();
	    	}
	    };
	    Page<Scale> list = getRepository().findAll(specification, pageable);
		return new PagedList<Scale>(list);
//		return scaleList;
	}

	@Override
	public PagedList<Scale> findPageList(PageRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Scale update(Scale args) {
		// TODO Auto-generated method stub
		return null;
	}
}
